package com.itboye.lottery.activity;

import android.content.Intent;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.Html;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.itboye.lottery.base.BaseActivity;
import com.itboye.lottery.R;
import com.itboye.lottery.activity.daletou.DaLeTouMainActivity;
import com.itboye.lottery.activity.shuangseqiu.ShuangSeQiuMainActivity;
import com.itboye.lottery.adapter.TouZhuListAdapter;
import com.itboye.lottery.alert.ByAlert;
import com.itboye.lottery.bean.CodeBean;
import com.itboye.lottery.bean.OrderBean;
import com.itboye.lottery.callback.PayCallBack;
import com.itboye.lottery.dialog.PayDialog;
import com.itboye.lottery.presenter.UserPresenter;
import com.itboye.lottery.retrofit.ResponseCallback;
import com.itboye.lottery.utils.ConstUrl;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.HashMap;

import static com.itboye.lottery.utils.BetSelectMatches.randomCodeTotal;
import static com.itboye.lottery.utils.CodeUtil.randomCommon;

public class
TouZhuListActivity extends BaseActivity implements ResponseCallback {

    RecyclerView rv_touzhu_list;
    //    ArrayList<HashMap<String, Object>> codeBeanArrayList;
    TextView tv_bottom_sure;
    private TouZhuListAdapter touzhuListAdapter;
    UserPresenter userPresenter;
    int multiple;//倍数
    ImageView iv_bottom_reduce, iv_bottom_increase, iv_bottom_reduce_multiple, iv_bottom_increase_multiple;
    CheckBox tv_jixuan;
    boolean isColorBall = true;
    TextView tv_jixuan_1, tv_jixuan_5, tv_manunal_choose;
    private ArrayList<CodeBean> randomRedCode;
    private ArrayList<CodeBean> randomBlueCode;
    private String num;
    EditText tv_bottom_beishu_multiple, tv_bottom_qishu_value;
    TextView tv_bottom_total;
    private int totalZhuShu;
    private int qishu;
    TextView tv_bottom_guize;

    public static TouZhuListActivity activity;
    TextView tv_end;

    @Override
    protected void initData() {
        activity = this;
        initRecyclerData();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        initRecyclerData();
    }

    private void initRecyclerData() {
//        codeBeanArrayList = new ArrayList<>();
        userPresenter = new UserPresenter(this);
        multiple = getIntent().getIntExtra("multiple", 1);
        isColorBall = getIntent().getBooleanExtra("type", true);//判断是从双色球进入还是从大乐透进入
//        codeBeanArrayList = (ArrayList<HashMap<String, Object>>) getIntent().getSerializableExtra("arrayCode");
        tv_end.setText(getIntent().getStringExtra("end_time"));
        rv_touzhu_list.setLayoutManager(new LinearLayoutManager(this));
        rv_touzhu_list.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
        touzhuListAdapter = new TouZhuListAdapter(this, randomCodeTotal);
        touzhuListAdapter.setLotteryType(isColorBall);
        rv_touzhu_list.setAdapter(touzhuListAdapter);
        setTotalMultibalAndBetZhuShuAndMoney();
        tv_bottom_beishu_multiple.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                setTotalMultibalAndBetZhuShuAndMoney();
            }
        });
        tv_bottom_qishu_value.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                setTotalMultibalAndBetZhuShuAndMoney();
            }
        });
    }

    private String getNumStrForDaLeTou() {
        if (randomCodeTotal == null) {
            return null;
        }
        if (randomCodeTotal.size() <= 0) {
            return null;
        }
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("[");
        for (int i = 0; i < randomCodeTotal.size(); i++) {
            Object arrayListHashMap = randomCodeTotal.get(i);
            ArrayList<CodeBean> redCodeBeanArrayList = ((HashMap<String, ArrayList<CodeBean>>) arrayListHashMap).get("red");//红色码
            ArrayList<CodeBean> redTuoCodeBeanArrayList = ((HashMap<String, ArrayList<CodeBean>>) arrayListHashMap).get("red_tuo");//红色拖码
            ArrayList<CodeBean> blueCodeBeanArrayList = ((HashMap<String, ArrayList<CodeBean>>) arrayListHashMap).get("blue");//蓝色胆
            ArrayList<CodeBean> blueTuoCodeBeanArrayList = ((HashMap<String, ArrayList<CodeBean>>) arrayListHashMap).get("blue_tuo");//蓝色托码
            //红胆
            for (int i1 = 0; i1 < redCodeBeanArrayList.size(); i1++) {
                if (i1 == 0) {
                    stringBuffer.append("\"");
                }
                CodeBean codeBean = redCodeBeanArrayList.get(i1);
                stringBuffer.append(codeBean.getCodeValue());
                if (i1 != redCodeBeanArrayList.size() - 1) {
                    stringBuffer.append(",");
                }
            }
            //红托
            if (redTuoCodeBeanArrayList != null) {
                for (int i1 = 0; i1 < redTuoCodeBeanArrayList.size(); i1++) {
                    if (i1 == 0) {
                        stringBuffer.append("#");
                    }
                    CodeBean codeBean = redTuoCodeBeanArrayList.get(i1);
                    stringBuffer.append(codeBean.getCodeValue());
                    if (i1 != redTuoCodeBeanArrayList.size() - 1) {
                        stringBuffer.append(",");
                    }
                }
            }
            //蓝胆
            if (blueCodeBeanArrayList != null) {
                for (int i1 = 0; i1 < blueCodeBeanArrayList.size(); i1++) {
                    CodeBean codeBean = blueCodeBeanArrayList.get(i1);
                    if (i1 == 0) {
                        stringBuffer.append("|");
                    }
                    stringBuffer.append(codeBean.getCodeValue());
                    if (i1 != blueCodeBeanArrayList.size() - 1) {
                        stringBuffer.append(",");
                    }
                }
            }
            //蓝托
            if (blueTuoCodeBeanArrayList != null) {
                for (int i1 = 0; i1 < blueTuoCodeBeanArrayList.size(); i1++) {
                    CodeBean codeBean = blueTuoCodeBeanArrayList.get(i1);
                    if (i1 == 0) {
                        stringBuffer.append("#");
                    }
                    stringBuffer.append(codeBean.getCodeValue());
                    if (i1 != blueTuoCodeBeanArrayList.size() - 1) {
                        stringBuffer.append(",");
                    }
                }

            }
            if (i != randomCodeTotal.size() - 1) {
                stringBuffer.append("\",");
            }
        }
        stringBuffer.append("\"]");
        Log.v("code_count", stringBuffer.toString());
        return stringBuffer.toString();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_tou_zhu_list;
    }

    CheckBox cb_agree_xieyi;

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_bottom_sure:
                if (!cb_agree_xieyi.isChecked()) {
                    ByAlert.alert("请先同意服务协议");
                    return;
                }
                if (Integer.parseInt(tv_bottom_beishu_multiple.getText().toString()) <= 0) {
                    ByAlert.alert("倍数不能小于或等于0");
                    return;
                }
                //["1,2,3,4,5,6,33|1,16","1,2,3,4,5,6|16","1,2,3,4,5#6,8,33,32,31,30|1,16"]
                //开始投注  生成双色球订单
                /**
                 * num	T文本	是
                 * 投注号码
                 * multiple	T文本	是
                 * 倍数（1-99）
                 * push_number	T文本	是
                 * 追号期数
                 * is_rand	T文本	是
                 * 追号是否随机
                 * is_stop	T文本	是
                 * 中奖满多少后是否停止
                 * stop_money	T文本	是
                 * 中奖多少金额后停止
                 */
                //获取选中号码 并进行格式化
                int qishu = Integer.parseInt(tv_bottom_qishu_value.getText().toString());
                if (isColorBall) {
                    num = getNumStrForColorBall();//双色球号码格式化
                    userPresenter.createOrderForColorBall(num, multiple, qishu + "", tv_jixuan.isChecked() ? 1 : 0, tv_jixuan.isChecked() ? 1 : 0, 0);
                } else {
                    num = getNumStrForDaLeTou();
                    userPresenter.createOrderForDaLeTou(num, multiple, qishu + "", tv_jixuan.isChecked() ? 1 : 0, tv_jixuan.isChecked() ? 1 : 0, 0);
                }
                if (num == null) {
                    ByAlert.alert("号码有误");
                }
                break;
            case R.id.iv_touzhu_list_delete:
                int position = Integer.valueOf(view.getTag().toString());
                for (int i = 0; i < randomCodeTotal.size(); i++) {
                    if (i == position) {
                        randomCodeTotal.remove(i);
                        break;
                    }
                }
                touzhuListAdapter.notifyDataSetChanged();
                setTotalMultibalAndBetZhuShuAndMoney();
                break;
            case R.id.iv_bottom_reduce:
                if (Integer.valueOf(tv_bottom_qishu_value.getText().toString()) > 1) {
                    tv_bottom_qishu_value.setText("" + (Integer.valueOf(tv_bottom_qishu_value.getText().toString()) - 1));
                    setTotalMultibalAndBetZhuShuAndMoney();
                }
                break;
            case R.id.iv_bottom_increase:
                if (Integer.valueOf(tv_bottom_qishu_value.getText().toString()) < 100) {
                    tv_bottom_qishu_value.setText("" + (Integer.valueOf(tv_bottom_qishu_value.getText().toString()) + 1));
                    setTotalMultibalAndBetZhuShuAndMoney();
                }
                break;
            case R.id.tv_jixuan_1:
                //加机选1注
                jixuan(1);
                break;
            case R.id.tv_jixuan_5:
                //加机选5注
                jixuan(5);
                break;
            case R.id.tv_manunal_choose:
//                finish();
                //手动选号
                if (isColorBall) {
                    if (ShuangSeQiuMainActivity.Companion.getActivity() != null) {
                        ShuangSeQiuMainActivity.Companion.setClear(false);
                        ShuangSeQiuMainActivity.Companion.getActivity().finish();
                    }
                    startActivity(new Intent(this, ShuangSeQiuMainActivity.class));
                } else {
                    if (DaLeTouMainActivity.Companion.getActivity() != null) {
                        DaLeTouMainActivity.Companion.setClear(false);
                    }
                    startActivity(new Intent(this, DaLeTouMainActivity.class));
                }
                break;
            case R.id.iv_bottom_reduce_multiple:
                if (Integer.parseInt(tv_bottom_beishu_multiple.getText().toString()) > 1) {
                    tv_bottom_beishu_multiple.setText(((Integer.parseInt(tv_bottom_beishu_multiple.getText().toString()) - 1) + ""));
                    setTotalMultibalAndBetZhuShuAndMoney();
                }
                break;
            case R.id.iv_bottom_increase_multiple:
                if (Integer.parseInt(tv_bottom_beishu_multiple.getText().toString()) < 100) {
                    tv_bottom_beishu_multiple.setText(((Integer.parseInt(tv_bottom_beishu_multiple.getText().toString()) + 1) + ""));
                    setTotalMultibalAndBetZhuShuAndMoney();
                }
                break;
            case R.id.tv_bottom_guize://规则说明
                startActivity(new Intent(this, WebActivity.class).putExtra("title", "玩法说明").putExtra("url", ConstUrl.play_method_url + "?type=" + (isColorBall ? ConstUrl.TYPE_SHUANGSEQIU : ConstUrl.TYPE_DALETOU)));
                break;
        }
    }

    public void clearAllChecked(View view) {
        if (randomCodeTotal != null) {
            randomCodeTotal.clear();
        }
        if (touzhuListAdapter != null) {
            touzhuListAdapter.notifyDataSetChanged();
        }
    }

    public void toXieYi(View view) {
        startActivity(new Intent(this, WebActivity.class).putExtra("title", "服务协议").putExtra("url", ConstUrl.SERVICE_XIEYI));
    }

    private void setTotalMultibalAndBetZhuShuAndMoney() {
        totalZhuShu = touzhuListAdapter.caculateTotalBet();
        if (!TextUtils.isEmpty(tv_bottom_beishu_multiple.getText())) {
            multiple = Integer.parseInt(tv_bottom_beishu_multiple.getText().toString());
        }
        if (!TextUtils.isEmpty(tv_bottom_qishu_value.getText())) {
            qishu = Integer.parseInt(tv_bottom_qishu_value.getText().toString());
        }
        tv_bottom_total.setText(Html.fromHtml("<font color='red'>" + totalZhuShu * multiple * qishu * 2 + "元</font><br>" + String.format("%1$d注 %2$d倍 %3$d期", totalZhuShu, multiple, qishu)));
    }

    private void jixuan(int count) {
        for (int i = 0; i < count; i++) {
            int redCount, blueCount;
            if (isColorBall) {
                redCount = 6;
                blueCount = 1;
            } else {
                redCount = 5;
                blueCount = 2;
            }
            //生成红色号码
            randomRedCode = randomCommon(1, 33, redCount, 0);//添加机选生成红
            //生成蓝色号码
            randomBlueCode = randomCommon(1, 12, blueCount, 2, randomRedCode);//添加机选生成蓝
            HashMap<String, Object> hash = new HashMap<>();
            hash.put("red", randomRedCode);
            hash.put("blue", randomBlueCode);
            hash.put("zhushu", 1);
            randomCodeTotal.add(hash);
        }
        touzhuListAdapter.notifyDataSetChanged();
        setTotalMultibalAndBetZhuShuAndMoney();
    }

    private String getNumStrForColorBall() {
        if (randomCodeTotal == null) {
            return null;
        }
        if (randomCodeTotal.size() <= 0) {
            return null;
        }
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("[");
        for (int i = 0; i < randomCodeTotal.size(); i++) {
            Object arrayListHashMap = randomCodeTotal.get(i);
            ArrayList<CodeBean> redCodeBeanArrayList = ((HashMap<String, ArrayList<CodeBean>>) arrayListHashMap).get("red");//红色码
            ArrayList<CodeBean> redTuoCodeBeanArrayList = ((HashMap<String, ArrayList<CodeBean>>) arrayListHashMap).get("red_tuo");//红色拖码
            ArrayList<CodeBean> blueCodeBeanArrayList = ((HashMap<String, ArrayList<CodeBean>>) arrayListHashMap).get("blue");//红色拖码
            //红色码数据集
            for (int i1 = 0; i1 < redCodeBeanArrayList.size(); i1++) {
                if (i1 == 0) {
                    stringBuffer.append("\"");
                }
                CodeBean codeBean = redCodeBeanArrayList.get(i1);
                stringBuffer.append(codeBean.getCodeValue());
                if (i1 != redCodeBeanArrayList.size() - 1) {
                    stringBuffer.append(",");
                }
            }
            //托马数据集
            if (redTuoCodeBeanArrayList != null) {
                for (int i1 = 0; i1 < redTuoCodeBeanArrayList.size(); i1++) {
                    if (i1 == 0) {
                        stringBuffer.append("#");
                    }
                    CodeBean codeBean = redTuoCodeBeanArrayList.get(i1);
                    stringBuffer.append(codeBean.getCodeValue());
                    if (i1 != redTuoCodeBeanArrayList.size() - 1) {
                        stringBuffer.append(",");
                    }
                }
            }

            for (int i1 = 0; i1 < blueCodeBeanArrayList.size(); i1++) {
                CodeBean codeBean = blueCodeBeanArrayList.get(i1);
                if (i1 == 0) {
                    stringBuffer.append("|");
                }
                stringBuffer.append(codeBean.getCodeValue());
                if (i1 != blueCodeBeanArrayList.size() - 1) {
                    stringBuffer.append("\",");
                }
            }
            if (i != randomCodeTotal.size() - 1) {
                stringBuffer.append("\",");
            }
        }

        stringBuffer.append("\"]");

        Log.v("code_count", stringBuffer.toString());
        return stringBuffer.toString();
    }

    @Override
    public void success(@NotNull Object o, @NotNull String requestSuccessType) {
        if (requestSuccessType == userPresenter.createOrderForColorBall_SUCCESS || requestSuccessType == userPresenter.createOrderForDaLeTou_SUCCESS) {
            OrderBean orderBean = (OrderBean) o;
            PayDialog surePay = new PayDialog(this, true);
            surePay.setAmount(orderBean.getAmount());
            surePay.setOrderBean(orderBean);
            surePay.setCallBack(new PayCallBack() {
                @Override
                public void paySuccess() {
                    ShuangSeQiuMainActivity.Companion.setClear(true);
                    finish();
                }

                @Override
                public void payFail(String msg) {
                    ShuangSeQiuMainActivity.Companion.setClear(true);
                }
            });
            surePay.show();
        }
    }

    @Override
    public void fail(int code, @NotNull Object msg, @NotNull String requestErrorType) {
        if (requestErrorType == userPresenter.createOrderForColorBall_FAIL || requestErrorType == userPresenter.createOrderForDaLeTou_FAIL) {
            ByAlert.alert(msg);

        }
    }
}
